package com.nulldev.util.web.nTube.pages;

import com.nulldev.util.languages.json.uniapi.UniJsonValue;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.legacyPages.v1.RequestType;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;
import com.nulldev.util.web.YouTubeExtractor.comments.YTComment;
import com.nulldev.util.web.YouTubeExtractor.comments.YTComments;
import com.nulldev.util.web.YouTubeExtractor.comments.YTComments.YTCommentInitData;
import com.nulldev.util.web.YouTubeExtractor.comments.YTComments.YouTubeCommentResult;

public class GetCommentsPage extends HttpPage3 {

	public GetCommentsPage() {
		super("/api/get_comments");
		super.setCachingMethod(CachingMethod.NO_CACHE);
		super.setUseJSONCaptchaPage(true);
	}

	private static final String JSON_MIME = "application/json; charset=utf-8";

	@SuppressWarnings("resource")
	@Override
	public Response onRequest(final Request request) {
		if (!request.getType().equals(RequestType.POST)) {
			return new Response(405);
		}
		if (!request.hasInputStream()) {
			return new Response(411);
		}
		final String body = toString(request.getInputStream());
		if (!body.startsWith("{") && !body.endsWith("}")) {
			return new Response(400);
		}
		final UniJsonValue object = UniJsonValue.parse(body);
		final UniJsonValue response = UniJsonValue.object();
		final YouTubeCommentResult ytc = YTComments.getComments(new YTCommentInitData(object));
		if (ytc == null) {
			return new Response(400);
		}
		if (ytc.hasCont()) {
			response.add("cont", ytc.getCont());
		}
		response.add("isDisabled", ytc.isCommentsDisabled());
		final UniJsonValue comments = UniJsonValue.array(ytc.getComments().size());
		for (final YTComment comment : ytc.getComments()) {
			final UniJsonValue m = UniJsonValue.object();
			m.add("author", comment.getAuthorName());
			m.add("authorURL", comment.getAuthorThumbnail());
			m.add("comment", comment.getComment());
			m.add("likes", comment.getLikes());
			m.add("authorLike", comment.isLiked());
			m.add("isHearted", comment.isHearted());
			m.add("pinnedByAuthor", comment.isPinned());
			m.add("author_verified", comment.isVerified());
			if (comment.hasReplies()) {
				m.add("replies", comment.getRepliesCont());
				m.add("replyCount", comment.getReplyCount());
			}
			comments.add(m);
		}
		response.add("comments", comments);
		ytc.clear();
		return new Response(200, response, response).setCustomMime(JSON_MIME);
	}

}
